const Inventory = require('../models/Inventory');
const InventoryTransaction = require('../models/InventoryTransaction');
const { Op } = require('sequelize');
const sequelize = require('../config/database');

// 创建库存
const createInventory = async (req, res) => {
  const t = await sequelize.transaction();
  try {
    const { productCode, productName, specification, unit, quantity, remark } = req.body;

    // 参数验证
    if (!productCode || !productName || !unit) {
      return res.status(400).json({
        code: 400,
        message: '商品编码、商品名称和单位为必填项'
      });
    }

    // 检查商品编码是否已存在
    const existingInventory = await Inventory.findOne({ where: { productCode } });
    if (existingInventory) {
      return res.status(400).json({
        code: 400,
        message: '商品编码已存在'
      });
    }

    // 创建库存记录
    const inventory = await Inventory.create({
      productCode,
      productName,
      specification,
      unit,
      quantity: quantity || 0,
      remark
    }, { transaction: t });

    // 如果有初始库存，创建初始化记录
    if (quantity && quantity > 0) {
      await InventoryTransaction.create({
        inventoryId: inventory.id,
        type: '初始化',
        quantity,
        beforeQuantity: 0,
        afterQuantity: quantity,
        remark: '初始库存'
      }, { transaction: t });
    }

    await t.commit();

    res.status(201).json({
      code: 200,
      message: '库存创建成功',
      data: inventory
    });

  } catch (error) {
    await t.rollback();
    console.error('创建库存错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 获取库存列表
const getInventories = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, productCode, productName } = req.body;
    const offset = (page - 1) * pageSize;

    // 构建查询条件
    const where = {};
    if (productCode) where.productCode = { [Op.like]: `%${productCode}%` };
    if (productName) where.productName = { [Op.like]: `%${productName}%` };

    const { count, rows } = await Inventory.findAndCountAll({
      where,
      attributes: {
        include: [
          [
            sequelize.fn('DATE_FORMAT', sequelize.col('Inventory.createdAt'), '%Y-%m-%d %H:%i:%s'),
            'createdAt'
          ],
          [
            sequelize.fn('DATE_FORMAT', sequelize.col('Inventory.updatedAt'), '%Y-%m-%d %H:%i:%s'),
            'updatedAt'
          ]
        ]
      },
      order: [['createdAt', 'DESC']],
      offset,
      limit: pageSize
    });

    res.json({
      code: 200,
      message: '获取库存列表成功',
      data: {
        total: count,
        page,
        pageSize,
        list: rows
      }
    });

  } catch (error) {
    console.error('获取库存列表错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 获取单个库存信息
const getInventoryById = async (req, res) => {
  try {
    const { id } = req.body;

    const inventory = await Inventory.findByPk(id);
    if (!inventory) {
      return res.status(404).json({
        code: 404,
        message: '库存记录不存在'
      });
    }

    res.json({
      code: 200,
      message: '获取库存信息成功',
      data: inventory
    });

  } catch (error) {
    console.error('获取库存信息错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 更新库存信息
const updateInventory = async (req, res) => {
  try {
    const { id, productCode, productName, specification, unit, remark } = req.body;

    const inventory = await Inventory.findByPk(id);
    if (!inventory) {
      return res.status(404).json({
        code: 404,
        message: '库存记录不存在'
      });
    }

    // 如果要更新商品编码，检查新编码是否已被使用
    if (productCode && productCode !== inventory.productCode) {
      const existingInventory = await Inventory.findOne({
        where: {
          productCode,
          id: { [Op.ne]: id }
        }
      });
      if (existingInventory) {
        return res.status(400).json({
          code: 400,
          message: '商品编码已被使用'
        });
      }
    }

    // 更新库存信息
    await inventory.update({
      productCode,
      productName,
      specification,
      unit,
      remark
    });

    res.json({
      code: 200,
      message: '库存信息更新成功',
      data: inventory
    });

  } catch (error) {
    console.error('更新库存信息错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 删除库存
const deleteInventory = async (req, res) => {
  try {
    const { id } = req.body;

    const inventory = await Inventory.findByPk(id);
    if (!inventory) {
      return res.status(404).json({
        code: 404,
        message: '商品不存在'
      });
    }

    await inventory.destroy(); // 软删除

    res.json({
      code: 200,
      message: '商品删除成功'
    });

  } catch (error) {
    console.error('删除商品错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 出入库操作
const handleInventoryTransaction = async (req, res) => {
  const t = await sequelize.transaction();
  try {
    const { inventoryId, type, quantity, remark } = req.body;

    if (!['入库', '出库'].includes(type)) {
      return res.status(400).json({
        code: 400,
        message: '操作类型无效'
      });
    }

    const inventory = await Inventory.findByPk(inventoryId, { transaction: t });
    console.log(inventoryId, inventory,'akwdbjhbwd');
    
    if (!inventory) {
      return res.status(404).json({
        code: 404,
        message: '库存记录不存在'
      });
    }

    // 出库时检查库存是否充足
    if (type === '出库' && inventory.quantity < quantity) {
      return res.status(400).json({
        code: 400,
        message: '库存不足'
      });
    }

    const beforeQuantity = inventory.quantity;
    const afterQuantity = type === '入库' 
      ? beforeQuantity + quantity 
      : beforeQuantity - quantity;

    // 更新库存数量
    await inventory.update({
      quantity: afterQuantity
    }, { transaction: t });

    // 创建交易记录
    await InventoryTransaction.create({
      inventoryId,
      type,
      quantity,
      beforeQuantity,
      afterQuantity,
      remark
    }, { transaction: t });

    await t.commit();

    res.json({
      code: 200,
      message: `${type}操作成功`,
      data: inventory
    });

  } catch (error) {
    await t.rollback();
    console.error('出入库操作错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 获取库存操作记录
const getInventoryTransactions = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, inventoryId, type, startDate, endDate } = req.body;
    const offset = (page - 1) * pageSize;

    // 构建查询条件
    const where = {};
    if (inventoryId) where.inventoryId = inventoryId;
    if (type) where.type = type;
    if (startDate && endDate) {
      where.createdAt = {
        [Op.between]: [startDate, endDate]
      };
    }

    const { count, rows } = await InventoryTransaction.findAndCountAll({
      where,
      include: [{
        model: Inventory,
        as: 'inventory',
        attributes: ['productCode', 'productName', 'specification', 'unit']
      }],
      attributes: {
        include: [
          [
            sequelize.fn('DATE_FORMAT', sequelize.col('InventoryTransaction.createdAt'), '%Y-%m-%d %H:%i:%s'),
            'createdAt'
          ],
          [
            sequelize.fn('DATE_FORMAT', sequelize.col('InventoryTransaction.updatedAt'), '%Y-%m-%d %H:%i:%s'),
            'updatedAt'
          ]
        ]
      },
      order: [['createdAt', 'DESC']],
      offset,
      limit: pageSize
    });

    res.json({
      code: 200,
      message: '获取操作记录成功',
      data: {
        total: count,
        page,
        pageSize,
        list: rows
      }
    });

  } catch (error) {
    console.error('获取操作记录错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

module.exports = {
  createInventory,
  getInventories,
  getInventoryById,
  updateInventory,
  deleteInventory,
  handleInventoryTransaction,
  getInventoryTransactions
};